//
//  ST_DTVoiceChatCell.swift
//  DrinkTogether
//
//  Created by DouLei on 2018/6/30.
//  Copyright © 2018 DouLei. All rights reserved.
//

import UIKit
import SwiftyAttributes
import SwifterSwift

private let VoiceDurationLabelWidth :CGFloat = 25

/**
 播放需要外层UI 提供协议
 */
protocol ST_d_t_voice_play_protocol:NSObjectProtocol {
    
    func playAudio(message:ST_DTChatMessage,currentCell:ST_DTVoiceChatCell)
    
    func stop_play_audio(message:ST_DTChatMessage)
}

class ST_DTVoiceChatCell: ST_DTChatCell {
    
    fileprivate lazy var voiceImages:[UIImage] = {
        let images = [ST_ImageUtils.imageName("n_私信_icon_语音03")!,ST_ImageUtils.imageName("n_私信_icon_语音02")!,ST_ImageUtils.imageName("n_私信_icon_语音01")!]
        return images
    }()
    
    fileprivate lazy var voice_mine_images:[UIImage] = {
        let images = [ST_ImageUtils.imageName("n_私信_icon_语音_mine03")!,ST_ImageUtils.imageName("n_私信_icon_语音_mine02")!,
                      ST_ImageUtils.imageName("n_私信_icon_语音_mine01")!]
        return images
    }()

    fileprivate lazy var voice_image_view:UIImageView = {
        let control = UIImageView()
        control.animationRepeatCount = 0
        control.animationDuration = 1
        return control
    }()
    
    fileprivate lazy var voice_back_view:UIView = {
        let control = UIView()
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(tap_voice_hanlde))
        control.cornerRadius = 20
        control.addGestureRecognizer(tap)
        return control
    }()
    
    fileprivate lazy var voice_duration_label:UILabel = {
        let control = UILabel()
        control.textColor = Color.init(hex: 0x8290A5)!
        control.font = UIFont.systemFont(ofSize: 12)
        return control
    }()
    
    
    fileprivate lazy var normal_left_attri:[Attribute] = [.font(UIFont.systemFont(ofSize: 12)),.textColor(Color.init(hex: 0x8290A5)!),.paragraphStyle(normal_left_paragraph_style)]
    
    fileprivate lazy var normal_right_attri:[Attribute] = [.font(UIFont.systemFont(ofSize: 12)),.textColor(Color.white),.paragraphStyle(normal_right_paragraph_style)]
    
    fileprivate lazy var normal_right_paragraph_style:ParagraphStyle = {
        let p = NSParagraphStyle.create_line_spacing_paragraph_style(lineSpacing: 0)
        p.alignment = .right
        return p
    }()
    
    fileprivate lazy var normal_left_paragraph_style:ParagraphStyle = {
        let p = NSParagraphStyle.create_line_spacing_paragraph_style(lineSpacing: 0)
        p.alignment = .left
        return p
    }()
    
    
    
    fileprivate lazy var refuse_attri:[Attribute] = [.font(UIFont.systemFont(ofSize: 12)),.textColor(Color.red)]

    weak var playDelegate:ST_d_t_voice_play_protocol?
    
    override func commonInit(){
    
        super.commonInit()
        
        self.contentView.addSubview(voice_back_view)
        self.voice_back_view.addSubview(voice_image_view)
        
        self.voice_back_view.addSubview(voice_duration_label)
        
    }
    
    
    override var message: ST_DTChatMessage!{
        didSet{
            
            setDefaultValue()
            
            self.uuid = message.uuid
            
            if message.audioPlaying{
                voice_image_view.startAnimating()
            }else{
                voice_image_view.stopAnimating()
            }
            
            if let check = message.passedCheck , check == false{
                
                voice_back_view.snp.updateConstraints { (make) in
                    make.width.equalTo(120)
                }
                
                voice_duration_label.attributedText = "语音违规 ''".withAttributes(refuse_attri)
                
                if message.audioPlaying{
                    stop_play_audio()
                }
                
            }else {
                
                voice_back_view.snp.updateConstraints { (make) in
                    make.width.equalTo(message.audioWidth)
                }
                
                let normalAttri = message.direction == .send ? normal_right_attri : normal_left_attri
                
                voice_duration_label.attributedText = "\(message.voiceDuration)''".withAttributes(normalAttri)
                
            }
        }
    }
    
    
    fileprivate func setDefaultValue(){
        
        
        
        icon.sd_setImage(with: message.portraitUri.compress_image().url, for: UIControl.State.normal, completed: nil)
        
          if message.direction == .send{
              
              
              voice_back_view.backgroundColor = Color.init(hexString: "#FEC207")
              
              voice_image_view.animationImages = self.voice_mine_images
              
              voice_image_view.image = self.voice_mine_images.first
              
              
          }else{
              
              voice_image_view.animationImages = self.voiceImages
              
              voice_image_view.image = self.voiceImages.first
              
              voice_back_view.backgroundColor = Color.init(hex: 0xF2F4F7)!
              
          }
        
    }
    
    
//    MARK: - Event
   
    
    @objc func tap_voice_hanlde(){
        
        if let check = message.passedCheck,check == false{
            
            if message.audioPlaying{
                stop_play_audio()
            }

            return
        }
        
        
        if let vc = self.parentViewController as? ST_PrivateChatViewController{
            vc.dismissMessageToolBar()
        }
        
        
        if message.audioPlaying{
            stop_play_audio()
        }else{
            start_play_audio()
        }
    }
    func start_play_audio() {
        message.audioPlaying = true
        voice_image_view.startAnimating()


        
        self.playDelegate?.playAudio(message: self.message, currentCell: self)
        
    }
    
    func stop_play_animation(){
        message.audioPlaying = false
        voice_image_view.stopAnimating()
    }
    
    func stop_play_audio() {
        
        stop_play_animation()
        
        self.playDelegate?.stop_play_audio(message: self.message)
        
    }
    
}




//MARK: - LeftCell

class ST_DTVoiceChatLeftCell: ST_DTVoiceChatCell {
    
    override func commonInit() {
        super.commonInit()
        
        icon.snp.makeConstraints { (make) in
            make.width.height.equalTo(40)
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(15)
        }
        
        voice_back_view.snp.makeConstraints { (make) in
            make.height.equalTo(44)
            make.width.equalTo(70 + CGFloat(150/60.0)*CGFloat(1))
            make.left.equalTo(icon.snp.right).offset(10)
            make.top.equalTo(icon)
        }
        
        voice_image_view.snp.makeConstraints { (make) in
            make.left.equalTo(voice_back_view).offset(17)
            make.top.equalToSuperview().offset(12)
            make.height.width.equalTo(20)
        }
        
        voice_duration_label.snp.makeConstraints { (make) in
            make.left.equalTo(voice_image_view.snp.right).offset(5)
            make.top.equalToSuperview().offset(12)
            make.height.equalTo(20)
        }
      
        self.contentView.addSubview(tailView)
        tailView.snp.makeConstraints { (make) in
            make.height.equalTo(17)
            make.top.equalTo(voice_back_view.snp.bottom).offset(5)
            make.left.equalTo(voice_back_view)
        }
    }
    
    fileprivate lazy var tailView:ST_ChatMessageTailControl = {
         let control = ST_ChatMessageTailControl()
          return control
      }()
    
    override var message: ST_DTChatMessage!{
        didSet{
         
            tailView.model = self.message.tail
            
        }
    }
}





//MARK: - RightCell

class ST_DTVoiceChatRightCell: ST_DTVoiceChatCell {
    
    override func commonInit() {
        super.commonInit()
        
        icon.removeFromSuperview()
        
        voice_back_view.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-30)
            make.top.equalToSuperview().offset(15)
            make.height.equalTo(44)
            make.width.equalTo(70 + CGFloat(150/60.0)*CGFloat(1))
        }
        
        voice_image_view.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-17)
            make.top.equalToSuperview().offset(12)
            make.height.width.equalTo(20)
        }
        
        voice_duration_label.snp.makeConstraints { (make) in
            make.height.equalTo(20)
            make.top.equalToSuperview().offset(12)
            make.right.equalTo(voice_image_view.snp.left).offset(-5)
        }
        
        contentView.addSubview(upload_error_btn)
        upload_error_btn.snp.makeConstraints { (make) in
            make.right.equalTo(voice_back_view.snp.left).offset(-10)
            make.centerY.equalTo(voice_back_view)
            make.width.height.equalTo(ST_DTChatCell.uploadErrorBtnSize)
        }
        
        
        
        contentView.addSubview(uploadIndicator)
        uploadIndicator.snp.makeConstraints { (make) in
            make.centerY.equalTo(voice_back_view)
            make.right.equalTo(voice_back_view.snp.left).offset(-8)
        }
    }
    
   
    override func setting_uplaod_status() {
        
        super.setting_uplaod_status()
        
        if message.uploadStatus == .uploading {
            
            uploadIndicator.startAnimating()
            
        }else{
            uploadIndicator.stopAnimating()
        }
        
        upload_error_btn.isHidden = message.uploadStatus != .failure
    }
}
